package com.sskj.trafficcontrol.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.sskj.trafficcontrol.consts.AppRequestConsts;
import com.sskj.trafficcontrol.consts.ResultJsonUtil;
import com.sskj.trafficcontrol.model.pojo.TcCitys;
import com.sskj.trafficcontrol.model.vo.LuBangXianingInfoVO;
import com.sskj.trafficcontrol.service.TrafficControlService;
import com.sskj.trafficcontrol.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;


@RestController
@RequestMapping(value = "/trafficDttailControl", produces = AppRequestConsts.CONTENT_TYPE_JSON, method = RequestMethod.POST)
public class TrifficDetailController {

    @Autowired
    private TrafficControlService trafficControlService;

    /*
     * @author : zhangHaiWen
     * @date   : 2019/2/27 20:12
     * @desc   : 获取限行详情
     * @param  :  * @param null
     * @return :  Json
     */
    @RequestMapping(value = "/detail")
    public String getTrifficDetail(@RequestBody String cityNameStr) {
        JSONObject cityName = (JSONObject) JSONObject.parse(cityNameStr);
        String reqCityName = cityName.get("cityName").toString();
        LuBangXianingInfoVO cityXianxingInfo = null;
        if (!cityNameStr.equals("") && cityNameStr != null) {
            TcCitys tcCitys = trafficControlService.findByCityName(reqCityName);
            cityXianxingInfo = LuBangXianxingUtil.getCityXianxingInfo(tcCitys.getCity());
        }
        return ResultJsonUtil.buildSuccessDataJson(cityXianxingInfo);
    }

    /*
     * @author : zhangHaiWen
     * @date   : 2019/2/27 22:08
     * @desc   :  获取程序的小程序二维码
     * @param  :  * @param null
     * @return :
     */
    @RequestMapping(value = "/getUserQRcode")
    public String getTrifficTest(@RequestBody String openIdStr) {
        JSONObject object = (JSONObject) JSONObject.parse(openIdStr);
        String open_id = object.get("open_id").toString();
        WxPushServiceQcl wxPushServiceQcl = new WxPushServiceQcl();
        String access_token = wxPushServiceQcl.getAccess_token(getOpenIdutil.appid, getOpenIdutil.secret);
        String requestUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token;
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", open_id);
            paramJson.put("width", 430);
            paramJson.put("auto_color", true);
            printWriter.write(paramJson.toString());
            // flush输出流的缓冲

            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            /*
            //设置文件夹地址
            String filePath = "http://47.95.115.232:8080/img/tempImg/";
            long time = new Date().getTime();
            String fileName = open_id+"_"+time+".jpg";
            int i = saveToImgByInputStream(bis, filePath, fileName);
            */
            BASE64Encoder encoder = new BASE64Encoder();
            byte[] bytes = null;
            try {
                bytes = input2byte(bis);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String encode = encoder.encode(bytes);
            return encode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * input 转 byte[]
     * @param inStream
     * @return
     * @throws IOException
     */
    public static final byte[] input2byte(InputStream inStream)
            throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }


    /* @param instreams 二进制流
     * @param imgPath 图片的保存路径
     * @param imgName 图片的名称
     * @return
     *      1：保存正常
     *      0：保存失败
     */
    public static int saveToImgByInputStream(InputStream instreams,String imgPath,String imgName) {
        int stateInt = 1;
        if (instreams != null) {
            try {
                File file = new File(imgPath + imgName); //可以是任何图片格式.jpg,.png等
                FileOutputStream fos = new FileOutputStream(file);

                byte[] b = new byte[1024];
                int nRead = 0;
                while ((nRead = instreams.read(b)) != -1) {
                    fos.write(b, 0, nRead);
                }
                fos.flush();
                fos.close();
            } catch (Exception e) {
                stateInt = 0;
                e.printStackTrace();
            } finally {
                try {
                    instreams.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return stateInt;
    }
}
